<template>
  <div class="container">
    <!-- 试题录入 -->
    <el-card>
      <div slot="header">
        <h3>{{ $route.query.id ? '试题修改' : '试题录入' }}</h3>
      </div>
      <el-form ref="form" :model="form" :rules="testRules" label-width="80px">
        <el-form-item label="学科:" prop="subjectID" label-width="100px">
          <el-select v-model="form.subjectID" placeholder="请选择" style="width: 35%" @change="getDirectList">
            <el-option v-for="sub in subList" :key="sub.value" :label="sub.label" :value="sub.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录:" prop="directoryID" label-width="100px">
          <el-select v-model="form.directoryID" placeholder="请选择" style="width: 35%">
            <el-option v-for="direct in directList" :key="direct.value" :label="direct.label" :value="direct.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业:" prop="enterpriseID" label-width="100px">
          <el-select v-model="form.enterpriseID" placeholder="请选择" style="width: 35%">
            <el-option v-for="com in enterpriseList" :key="com.id" :label="com.company" :value="com.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市:" label-width="100px">
          <el-select v-model="form.province" placeholder="请选择" style="width: 17%" @change="getCityList">
            <el-option v-for="(city, index) in provinceList" :key="index" :label="city" :value="city"></el-option>
          </el-select>
          <el-select v-model="form.city" placeholder="请选择" style="width: 17%; margin-left: 1%" v-if="form.province">
            <el-option v-for="(city, index) in cityList" :key="index" :label="city" :value="city"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="方向:" label-width="100px">
          <el-select v-model="form.direction" placeholder="请选择" style="width: 35%">
            <el-option v-for="d in direction" :key="d" :label="d" :value="d" />
          </el-select>
        </el-form-item>

        <el-form-item label="题型:" label-width="100px">
          <el-radio v-model="form.questionType" label="1">单选</el-radio>
          <el-radio v-model="form.questionType" label="2">多选</el-radio>
          <el-radio v-model="form.questionType" label="3">简答</el-radio>
        </el-form-item>

        <el-form-item label="难度:" label-width="100px">
          <el-radio v-model="form.difficulty" label="1">简单</el-radio>
          <el-radio v-model="form.difficulty" label="2">一般</el-radio>
          <el-radio v-model="form.difficulty" label="3">困难</el-radio>
        </el-form-item>

        <el-form-item label="题干:" label-width="100px" style="width: 60%">
          <quill-editor v-model="form.question" :options="editOptions" />
          <!-- @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @ready="onEditorReady($event)" -->
        </el-form-item>
        <!-- 单选 -->
        <el-form-item v-if="form.questionType === '1'" label="选项:" label-width="100px" style="width: 60%">
          <el-radio-group v-model="correctChosen">
            <el-row style="margin-bottom: 30px" type="flex" justify="center" align="middle" v-for="item in options" :key="item.id">
              <el-col>
                <el-radio :label="item.code">{{ item.code }}：&nbsp;<el-input v-model="item.title" placeholder="" /></el-radio>
                <!-- <el-radio :label="item.code" :value="item.isRight ? item.code : ''" style="margin-top: 10px; margin-bottom: 10px">{{ item.code }}：&nbsp;<el-input v-model="item.title" placeholder="" /></el-radio> -->
              </el-col>
              <el-col :span="6" :push="6" >
                <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="function (res, file) { return handleBannerSuccess(res, file, item)}">
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <i v-else class="avatar-uploader-icon">上传图片</i>
                </el-upload>
              </el-col>
            </el-row>
            <el-button icon="el-icon-plus" type="danger" :disabled="form.questionType === '1'">增加选项与答案</el-button>
          </el-radio-group>
        </el-form-item>

        <!-- 多选 -->
        <el-form-item v-else-if="form.questionType === '2'" label="多选选项:" label-width="100px" style="width: 60%">
          <el-checkbox-group v-model="correctChosenArr">
            <el-row style="margin-bottom: 30px" type="flex" justify="center" align="middle" v-for="item in options" :key="item.id">
              <el-col>
                <el-checkbox :label="item.code">{{ item.code }}：&nbsp;<el-input v-model="item.title" placeholder="" /></el-checkbox>
              </el-col>
              <el-col>
                <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="function (res, file) { return handleBannerSuccess(res, file, item)}">
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <i v-else class="avatar-uploader-icon">上传图片</i>
                </el-upload>
              </el-col>
            </el-row>
            <el-button icon="el-icon-plus" type="danger" :disabled="form.questionType === '1'" @click="addNewCheckBox">增加选项与答案</el-button>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="解析视频:" label-width="100px" style="width: 35%">
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>

        <el-form-item label="答案解析:" label-width="100px" style="width: 60%">
          <quill-editor v-model="form.answer" :options="editOptions" />
          <!-- @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @ready="onEditorReady($event)" -->
        </el-form-item>

        <el-form-item label="题目备注:" label-width="100px" style="width: 35%">
          <el-input type="textarea" v-model="form.remarks"></el-input>
        </el-form-item>

        <el-form-item label="试题标签:" label-width="100px">
          <el-select v-model="form.tags" multiple filterable allow-create default-first-option placeholder="请选择" style="width: 35%">
            <el-option v-for="tag in tagList" :key="tag.value" :label="tag.label" :value="tag.label"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label-width="100px">
          <el-button type="success" @click="onSubmit" v-if="$route.query.id">确认修改</el-button>
          <el-button type="primary" @click="onSubmit" v-else>确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.snow.css'
import { simple } from '@/api/hmmm/subjects'
import { simple as directSimple } from '@/api/hmmm/directorys'
import { simple as tagSimple } from '@/api/hmmm/tags'
import { list as enterpriseList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { detail, update, add } from '@/api/hmmm/questions'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      imageUrl: [],
      form: {
        subjectID: '', // 学科ID
        directoryID: '', //  目录ID
        directoryName: '', // 目录名字
        enterpriseID: '', // 企业
        province: '', // 地区
        city: '', // 城市
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', //  难度
        remarks: '', // 备注
        tags: [], // 标签
        videoURL: '', //  视频地址
        question: '', //  题干
        answer: '' // 答案解析
      },
      options: [
        { isRight: '', code: 'A', title: '', img: '' },
        { isRight: '', code: 'B', title: '', img: '' },
        { isRight: '', code: 'C', title: '', img: '' },
        { isRight: '', code: 'D', title: '', img: '' }
      ],
      subList: [], // 学科列表
      directList: [], // 目录列表
      tagList: [], // 标签列表
      enterpriseList: [], // 企业列表
      provinceList: [], // 地区列表
      cityList: [], // 城市列表
      direction, // 方向列表
      questionType, // 导入的题型列表
      difficulty, // 导入的困难程度列表
      correctChosen: 'A', // 默认选择A按钮
      correctChosenArr: ['A'],
      testRules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        directoryID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        correctChosen: [{ required: true, message: '请选择选项', trigger: 'change' }],
        correctChosenArr: [{ required: true, message: '请选择选项', trigger: 'change' }],
        videoURL: [{ required: true, message: '请输入视频地址', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入题目备注', trigger: 'blur' }],
        tags: [{ required: true, message: '请输入试题标签', trigger: 'blur' }]
      }, // 规则
      // 编辑器配置
      editor: {},
      // 编辑器配置
      editOptions: {
        // debug: 'info',
        modules: {
          toolbar: [['bold', 'italic', 'underline', 'strike'], [{ list: 'ordered' }, { list: 'bullet' }], ['blockquote'], ['code-block', 'image', 'link']]
        },
        // readOnly: false,
        placeholder: '',
        theme: 'snow'
      }
    }
  },
  // computed: {
  //   correctChosen () {
  //     if (this.form.questionType === '1') return []
  //   }
  // },
  watch: {
    correctChosen: {
      handler (val) {
        if (this.form.questionType === '1') {
          // this.correctChosen = 'A'
          this.options.forEach((item) => {
            item.isRight = 0
            if (item.code === val) {
              item.isRight = 1
            }
          })
        }
      },
      immediate: true
    },
    correctChosenArr: {
      handler (val) {
        this.options.forEach((item) => {
          item.isRight = 0
        })
        val.forEach((item) => {
          this.options.forEach((option) => {
            if (option.code === item) {
              console.log(option)
              option.isRight = 1
            }
          })
        })
      },
      immediate: true, //
      deep: true
    }
  },
  created () {
    this.getSubList()
    this.getEnterpriseList()
    this.getProvinceList()
    this.getDetailData()
  },
  methods: {
    // 提交按钮
    async onSubmit () {
      try {
        if (this.$route.query.id) {
          this.form.options = this.form.options.map(item => {
            if (item.isRight === 1) {
              item.isRight = true
            } else {
              item.isRight = false
            }
            return item
          })
          const { data } = await update({ ...this.correctChosen, ...this.form })
          if (data.success) {
            await this.$message.success('修改成功！')
          }
          this.$router.back()
        } else {
          this.form.options = this.options
          await add({
            subjectID: this.form.subjectID,
            catalogID: this.form.directoryID,
            enterpriseID: this.form.enterpriseID,
            province: this.form.province,
            city: this.form.city,
            direction: this.form.direction,
            questionType: this.form.questionType,
            difficulty: this.form.difficulty,
            question: this.form.question,
            options: this.form.options.map(item => {
              if (item.isRight === 1) {
                item.isRight = true
              } else {
                item.isRight = false
              }
              return item
            }),
            videoURL: this.form.videoURL,
            answer: this.form.answer,
            remarks: this.form.remarks,
            tags: this.form.tags.join(',')
          })
          await this.$message.success('添加成功')
          this.$router.push({ name: 'questions-list' })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取学科列表
    async getSubList () {
      const { data } = await simple()
      this.subList = data
    },
    // 根据学科ID获取目录列表
    async getDirectList (id) {
      const { data } = await directSimple({ subjectID: id })
      this.directList = data
      const res = await tagSimple({ subjectID: id })
      this.tagList = res.data
    },
    // 获取企业列表
    async getEnterpriseList () {
      const { data } = await enterpriseList({ pagesize: 1000 })
      this.enterpriseList = data.items
    },
    // 获取地区列表
    getProvinceList () {
      this.provinceList = provinces()
    },
    // 获取城市列表
    getCityList () {
      this.cityList = citys(this.form.province)
    },
    // // 获取目录详情
    // async detailDir (v) {
    //   try {
    //     const { data } = await detailDir({
    //       id: v
    //     })
    //     console.log(data)
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
    // ------------------------------------------------------------------------------------------------
    // 照片上传成功回调
    handleBannerSuccess (response, file, item) {
      item.img = window.URL.createObjectURL(file.raw)
    },
    // 根据路由参数，获取当前页面的数据
    async getDetailData () {
      try {
        if (this.$route.query.id) {
          const { data } = await detail({
            id: this.$route.query.id
          })
          this.form = data
          this.options = data.options
          this.getDirectList(data.subjectID)
          if (data.questionType === '1') {
            this.correctChosen = this.options.filter((item) => item.isRight)[0].code
          } else {
            this.correctChosenArr = []
            this.options.forEach((item) => {
              if (item.isRight) {
                this.correctChosenArr.push(item.code)
              }
            })
          }
          console.log(data)
        } else {
          return 'new'
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 点击新增按钮
    addNewCheckBox () {
      var num = 0
      this.options.forEach((item) => {
        num = item.code.charCodeAt() > num ? item.code.charCodeAt() : num
      })
      this.options.push({
        isRight: false,
        code: this.addNew(num),
        title: '', //
        img: ''
      })
    },
    addNew (v) {
      return String.fromCharCode(v + 1)
    }
    // // 编辑器相关方法
    // onEditorBlur (quill) {
    //   console.log('editor blur!', quill)
    // },
    // onEditorFocus (quill) {
    //   console.log('editor focus!', quill)
    // },
    // onEditorReady (quill) {
    //   console.log('editor ready!', quill)
    // },
    // onEditorChange ({ quill, html, text }) {
    //   console.log('editor change!', quill, html, text)
    //   this.question = html
    // }
  }
}
</script>

<style scoped lang='less'>
// 祛除背景颜色
/deep/ .el-alert--error.is-light {
  background-color: #ffffff;
  color: pink;
}
.container {
  padding: 15px 10px;
}

/deep/ .quill-editor .ql-container.ql-snow {
  height: 200px;
}
/deep/.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
}
.avatar-uploader-icon {
  font-size: 16px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  background-position: 0 0;
  background-size: cover;
}
</style>
